/**
 * User: jacek
 * Date: 2008-06-08
 * Time: 20:21:46
 */
package elka.isi.operator.writer;

import elka.isi.gene.AnimalGene;
import elka.isi.individual.AnimalIndividual;
import elka.isi.util.RWUtils;
import org.evolvica.core.IIndividualSet;
import org.evolvica.core.ISetIterator;

public class GeneticAttributesWriter extends EcosystemStateWriter {
	public GeneticAttributesWriter(String filename) {
		super(filename);
//		wylaczylem bo matlab nie lyka naglowkow /Zibi
//		writer.append(createHeaders("RB") + DELIMITER);
//		writer.append(createHeaders("W") + DELIMITER);
//		writer.append(createHeaders("RO"));
//		writer.append("\n");
	}

	public void write(IIndividualSet set) {

		int wolfCount = RWUtils.getWolves(set).size();
		int rabbitCount = RWUtils.getRabbits(set).size();
		int roeCount = RWUtils.getRoes(set).size();

		int avgRabbitGeneValues[] = new int[AnimalGene.GENOME_SIZE];
		int avgRoeGeneValues[] = new int[AnimalGene.GENOME_SIZE];
		int avgWolfGeneValues[] = new int[AnimalGene.GENOME_SIZE];

		for (ISetIterator it = set.iterator(); it.hasNext();) {
			AnimalIndividual individual = (AnimalIndividual) it.next();
			switch (individual.getSpecies()) {
			case AnimalIndividual.RABBIT:
				countSums(avgRabbitGeneValues, individual);
				break;
			case AnimalIndividual.ROE:
				countSums(avgRoeGeneValues, individual);
				break;
			case AnimalIndividual.WOLF:
				countSums(avgWolfGeneValues, individual);
				break;
			default:
				break;
			}
		}
		if (rabbitCount != 0) {
			countMeans(rabbitCount, avgRabbitGeneValues);
		}
		if (roeCount != 0) {
			countMeans(roeCount, avgRoeGeneValues);
		}
		if (wolfCount != 0) {
			countMeans(wolfCount, avgWolfGeneValues);
		}

		writer.append(formatValues(avgRabbitGeneValues)
				+ formatValues(avgWolfGeneValues)
				+ formatValues(avgRoeGeneValues) + "\n");

	}

	private void countMeans(int count, int[] geneValues) {
		for (int i = 0; i < AnimalGene.GENOME_SIZE; i++) {
			geneValues[i] /= count;
		}
	}

	private void countSums(int[] geneValues, AnimalIndividual individual) {
		for (int i = 0; i < AnimalGene.GENOME_SIZE; i++) {
			AnimalGene gene = (AnimalGene) individual.getGenotype();
			geneValues[i] += gene.getGene(i);
		}
	}

	private String formatValues(int[] geneValues) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < AnimalGene.GENOME_SIZE; i++) {
			sb.append(geneValues[i] + DELIMITER);
		}
		return sb.toString();
	}

	private String createHeaders(String p) {
		return p + "_SIZE" + DELIMITER + p + "_LLEN" + DELIMITER + p + "_MUS"
				+ DELIMITER + p + "_EYE" + DELIMITER + p + "_HEA" + DELIMITER
				+ p + "_SME" + DELIMITER + p + "_SMA" + DELIMITER + p + "_MEM"
				+ DELIMITER + p + "_MET";
	}

}
